<?php
namespace app\util;

use app\common\exception\ApiException;
use think\Log;

class Juhe
{

    /**
     * 请求接口返回内容
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */

    public static function Location( $params, $ispost = 0)
    {
        $url = "http://apis.juhe.cn/mobile/get";
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url.'?'.$params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

    /**
     * 发起http post请求
     */
    function request_post($url = '', $post_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $arr = [];
        foreach ($post_data as $key => $value) {
            $arr[] = $key.'='.$value;
        }
        $curlPost = implode('&', $arr);
        $postUrl = $url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$postUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    // 生成guid
    function guid(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12);
            return $uuid;
        }
    }

    // 生成签名
    function sign($data, $appKey) {
        $arr = [];
        foreach ($data as $key => $value) {
                $arr[] = $key.'='.$value;
        }
        $arr[] = 'key='.$appKey;
        $str = strtoupper(implode('&', $arr));
        return strtoupper(md5($str));
    }

    public  function  uuPrice($datas){
        header("Content-type: text/html; charset=utf-8");

        $guid = str_replace('-', '', $this->guid());

        $appid = config('uu.APPID');
        $appKey = config('uu.AppKey');
        $OpenId = config('uu.OpenId');
        $url = "http://openapi.uupaotui.com/v2_0/getorderprice.ashx";
        // POST数据
        $data = array(
            'origin_id'       => $datas['tradeNo'],
            'from_address'       => $datas['masterAddress'],
            'to_address'       => $datas['region'],
            'to_usernote'       => $datas['address'],
            'city_name'       => "萍乡市",
            'subscribe_type'       => 0,
            'coupon_id'       => -1,
            'send_type'       => 0,
            'to_lat'       => $datas['latitude'],
            'to_lng'       => $datas['longitude'],
            'from_lat'       => $datas['masterlatitude'],
            'from_lng'       => $datas['masterlongitude'],
            'coord_type' => 3,
            'nonce_str'   => strtolower($guid),
            'timestamp'   => time(),
            'openid'       => $OpenId,
            'appid'       => $appid,
        );
        ksort($data);
        $data['sign'] = $this->sign($data, $appKey);
        $res = $this->request_post($url, $data);
        $res = json_decode($res);
        $ret = [];
        if($res->return_code == 'ok' || $res->return_code == 'fail'){
            $ret['price_token'] = $res->price_token;
            $ret['total_money'] = $res->total_money;
            $ret['need_paymoney'] = $res->need_paymoney;
            $ret['total_priceoff'] = $res->total_priceoff;
            $ret['distance'] = $res->distance;
            $ret['freight_money'] = $res->freight_money;
        }else{
            log::write($res,'uuPriceError');
            throw new ApiException($res->return_msg, 200, ReturnCode::INVALID);
        }
        return $ret;
    }

    public  function  addUuOrder($datas){
        header("Content-type: text/html; charset=utf-8");

        $guid = str_replace('-', '', $this->guid());

        $appid = config('uu.APPID');
        $appKey = config('uu.AppKey');
        $OpenId = config('uu.OpenId');
        $url = config('uu.url');
        $url = "http://openapi.uupaotui.com/v2_0/addorder.ashx";
        // POST数据
        $data = array(
            'price_token'       => $datas['deliveryContent']['price_token'], //金额令牌
            'order_price'       => $datas['deliveryContent']['total_money'], //订单金额
            'balance_paymoney'       => $datas['deliveryContent']['need_paymoney'], //实际余额支付金额
            'receiver'       => $datas['consignee'], //收件人
            'receiver_phone'       => $datas['mobile'], //收件人电话
            'callback_url'       => $url, //回调地址
            'push_type'       => 2, //测试订单2  开放订单0
            'special_type'       => 0, //特殊处理类型，是否需要保温箱 1需要 0不需要
            'callme_withtake'       => 0, //取件是否给我打电话 1需要 0不需要
            'pubusermobile'       => $datas['masterMobile'], //发件人电话
            'nonce_str'   => strtolower($guid), //随机字符串
            'timestamp'   => time(),//时间戳
            'openid'       => $OpenId,//用户openid
            'appid'       => $appid,//
        );
        ksort($data);
        $data['sign'] = $this->sign($data, $appKey);
        $res = $this->request_post($url, $data);
        $res = json_decode($res);
        $ret = [];
        if($res->return_code == 'ok' || $res->return_code == 'fail' ){
            $ret = $res->ordercode;
        }else{
            log::write($res,'addUuOrderError');
            throw new ApiException($res->return_msg, 200, ReturnCode::INVALID);
        }
        return $ret;
    }

    public  function  cancel($datas){
        header("Content-type: text/html; charset=utf-8");

        $guid = str_replace('-', '', $this->guid());

        $appid = config('uu.APPID');
        $appKey = config('uu.AppKey');
        $OpenId = config('uu.OpenId');
        $url = "http://openapi.uupaotui.com/v2_0/cancelorder.ashx";
        // POST数据
        $data = array(
            'order_code'       => $datas['deliveryTradeNo'],
            'origin_id'       => $datas['tradeNo'],
            'reason'       => "测试",
            'nonce_str'   => strtolower($guid),
            'timestamp'   => time(),
            'openid'       => $OpenId,
            'appid'       => $appid,
        );
        ksort($data);
        $data['sign'] = $this->sign($data, $appKey);
        $res = $this->request_post($url, $data);
        $res = json_decode($res);

        if($res->return_code == 'ok' || $res->return_code == 'fail'){
            return $res;
        }else{
            log::write($res,'cancelError');
            throw new ApiException($res->return_msg, 200, ReturnCode::INVALID);
        }
    }


}
